#include "musicslider.h"
#include "ui_musicslider.h"
#include <QMouseEvent>

MusicSlider::MusicSlider(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MusicSlider)
{
    ui->setupUi(this);
    maxPos = ui->inLine->width();
}

MusicSlider::~MusicSlider()
{
    delete ui;
}

void MusicSlider::setStep(float ratio)
{
    currentPos = maxPos*ratio;
    moveSlider();
}

void MusicSlider::mouseMoveEvent(QMouseEvent *event)
{
    if(event->buttons() == Qt::LeftButton)
    {
        currentPos = event->pos().x();

        //验证合法
        currentPos = currentPos < 0 ? 0 : currentPos;
        currentPos = currentPos > maxPos ? maxPos : currentPos;

        moveSlider();
    }
}

void MusicSlider::mousePressEvent(QMouseEvent *event)
{
    currentPos = event->pos().x();
    //验证合法
    currentPos = currentPos < 0 ? 0 : currentPos;
    currentPos = currentPos > maxPos ? maxPos : currentPos;

    moveSlider();
}

void MusicSlider::mouseReleaseEvent(QMouseEvent *event)
{
    currentPos = event->pos().x();
    //验证合法
    currentPos = currentPos < 0 ? 0 : currentPos;
    currentPos = currentPos > maxPos ? maxPos : currentPos;

    moveSlider();

    //发送信号给MusicPlayer,设置歌曲播放进度
    emit musicSliderChanged(currentPos/(float)maxPos);
}

void MusicSlider::moveSlider()
{
    ui->outLine->setGeometry(ui->outLine->x(), ui->outLine->y(), currentPos, ui->outLine->height());
}
